/**
 * 教练注册页面
 */

import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, Input, Button, Image, Picker } from '@tarojs/components';

import ImageLoader from '../../components/ImageLoader';
import { uploadUserFile } from '../../contexts/store';
import type { RegionNode } from '../../types/cityBase';
import { getChinaCityListApi } from '../../api/cityApi';
import { IMAGE_BASE_URL } from '../../utils/common';
import { getBasesByCityApi, getCarLicensesApi } from '../../api/baseApi';
import ProvinceCitySelector from '../../components/ProvinceCitySelector';
import { registerCoachUserApi, getCoachRegisterApi } from '../../api/auth';
import { getIdCardOcrApi, getCoachLicenseOcrApi } from '../../api/common';


import './index.scss';


const CoachRegisterPage: React.FC = () => {
  const phone = Taro.getCurrentInstance().router?.params?.phone || '';
  const sessionKey = Taro.getCurrentInstance().router?.params?.sessionKey || '';
  const sessionKeyDecoded = decodeURIComponent(sessionKey);

  // 表单状态
  const [drivingSchool, setDrivingSchool] = useState('');
  const [simulationFee, setSimulationFee] = useState('');
  const [coachingAge, setCoachingAge] = useState('');
  const [city, setCity] = useState('');
  const [coachingType, setCoachingType] = useState<string>('');
  const [name, setName] = useState<string>('');
  const [gender, setGender] = useState<string>('');
  const [native, setNative] = useState<string>('');
  const [base_id, setBaseId] = useState<string>('');
  const [idUid, setIdUid] = useState<string>('');
  const [submitOver, setSubmitOver] = useState<boolean>(false);
  
  // 图片上传状态
  const [coachLicense, setCoachLicense] = useState<{ url: string; file_name?: string } | null>(null);
  const [idCardFront, setIdCardFront] = useState<{ url: string; file_name?: string } | null>(null);
  const [idCardBack, setIdCardBack] = useState<{ url: string; file_name?: string } | null>(null);
  const [avatar, setAvatar] = useState<{ url: string; file_name?: string } | null>(null);
  const [businessLicense, setBusinessLicense] = useState<{ url: string; file_name?: string } | null>(null);
  const [uploading, setUploading] = useState<boolean>(false);
  const [isEnglishTeaching, setIsEnglishTeaching] = useState<number>(0);

  // 控制字段显示状态
  const [showNameField, setShowNameField] = useState<boolean>(false);
  const [showGenderField, setShowGenderField] = useState<boolean>(false);
  const [showNativeField, setShowNativeField] = useState<boolean>(false);
  const [showCoachingTypeField, setShowCoachingTypeField] = useState<boolean>(false);
  const imageSaveParent = {
    "coachLicense": "coachLicense",
    "idCardFront": "coachIdCard", 
    "idCardBack": "coachIdCard", 
    "avatar": "coachAvatar", 
    "businessLicense": "coachBusiness"
  }
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [chinaCity, setChinaCity] = useState<any[]>([]);
  const [basesData, setBasesData] = useState<any[]>([]);
  const [carLicenseList, setCarLicenseList] = useState<any>(null);
  const [selectedRegionPath, setSelectedRegionPath] = useState<string[]>([]);

  const fetchCities = async () => {
    await getCarLicensesApi().then((resp) => {
      if (resp.code === 200 && resp.data) {
        setCarLicenseList(resp.data);
      }
    }).catch(err => {
      console.log("获取车辆执照数据失败");
    })

    try {
      Taro.showLoading({ title: '加载城市列表...' });
      const response = await getChinaCityListApi();
      if (response.code === 200) {
        setChinaCity(response.data);
      }
    } catch (error) {
      console.error('获取城市列表失败:', error);
      Taro.showToast({ title: '获取城市列表失败', icon: 'none' });
    } finally {
      Taro.hideLoading();
    }
  };

  const getCoachRegisterInfo = async () => {
    try {
      Taro.showLoading({ title: '加载教练注册信息...' });
      const response = await getCoachRegisterApi({
        phone: phone,
        session_key: sessionKeyDecoded
      });
      if (response.code === 200) {
        const data = response.data || {};
        setDrivingSchool(data.school || '');
        setSimulationFee(data.description || '');
        setCoachingAge(data.experience_years || '');
        setCoachingType(data.licenses || '');
        setName(data.username || '');
        setGender(data.gender || '');
        setNative(data.native || '');
        setCity(data.cityId);
        onCityChange([String(data.cityId)]);
        setSelectedRegionPath(data.cityCode || []);
        setIdCardFront(data.idCardFront ? { url: data.idCardFront } : null);
        setIdCardBack(data.idCardBack ? { url: data.idCardBack } : null);
        setAvatar(data.avatar ? { url: data.avatar } : null);
        setBusinessLicense(data.schoolCertificate ? { url: data.schoolCertificate } : null);
        setIsEnglishTeaching(data.englishTeaching || 0);
        setCoachLicense(data.certificate ? { url: data.certificate } : null)
        setSubmitOver(true);
        setBaseId(data.baseId || '');
      }
    } catch (error) {
      console.error('获取教练注册信息失败:', error);
      Taro.showToast({ title: '获取教练注册信息失败', icon: 'none' });
    } finally {
      Taro.hideLoading();
    }
  }

  // 获取城市列表
  useEffect(() => {
    fetchCities();
    getCoachRegisterInfo();
  }, []);

  /**
   * 处理城市变更
   */
  const onCityChange = async (cityIds: string[]) => {
    if (cityIds && cityIds.length > 0) {
      const cityId = cityIds[cityIds.length - 1];
      setCity(cityId);
      setBasesData([]);
      setBaseId("")
      try {
        await getBasesByCityApi([parseInt(cityId)])
          .then(res => {
            if (res.code == 200) {
              setBasesData(res.data);
            }else {
               Taro.showToast({
                title: '获取驾校列表失败，请稍后重试',
                icon: 'none'
              });
            }
          })
          .catch(error => {
            console.error('获取驾校列表失败:', error);
            Taro.showToast({
              title: '获取驾校列表失败，请稍后重试',
              icon: 'none'
            });
          });
      }catch (error) {
        console.error('获取驾校列表失败:', error);
        Taro.showToast({
          title: '获取驾校列表失败，请稍后重试',
          icon: 'none'
        });
      }
    }
  };

  /**
   * 处理地区选择
   * @param path 选择的地区ID路径
   * @param node 选择的节点信息
   * @param parentNode 父节点信息
   */
  const handleRegionSelect = (path: string[], node?: RegionNode, parentNode?: RegionNode | null) => {
    setSelectedRegionPath(path);
    onCityChange([String(node?.id)]);
    console.log('选择的地区路径:', path, node, parentNode);
  };

  const getCityName = (city: string) => {
    const cityId = parseInt(city);
    for (const province of chinaCity) {
      for (const city of province.children || []) {
        if (city.id === cityId) {
          return city.name;
        }
        for (const district of city.children || []) {
          if (district.id === cityId) {
            return `${city.name}${district.name}`;
          }
        }
      }
    }
    return '';
  }

  // 图片上传函数
  const handleImageUpload = async (type: 'coachLicense' | 'idCardFront' | 'idCardBack' | 'avatar' | 'businessLicense') => {
    try {
      // 检查是否已上传图片，如果已上传，提示是否替换
      const hasExistingImage = 
        (type === 'avatar' && avatar) ||
        (type === 'idCardFront' && idCardFront) ||
        (type === 'idCardBack' && idCardBack) ||
        (type === 'coachLicense' && coachLicense) ||
        (type === 'businessLicense' && businessLicense);
        
      if (hasExistingImage) {
        const confirmResult = await Taro.showModal({
          title: '提示',
          content: '确定要替换已上传的图片吗？',
          confirmText: '确定',
          cancelText: '取消',
        });
        
        if (!confirmResult.confirm) {
          return;
        }
      }

      await Taro.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          // 清除对应字段的错误提示
          if (formErrors[type]) {
            setFormErrors(prev => ({
              ...prev,
              [type]: ''
            }));
          }
          
          // 显示加载提示
          Taro.showLoading({
            title: '上传中...',
            mask: true
          });

          try {
            let fileType = tempFilePath.split(".").pop() || 'png';
            await uploadUserFile(tempFilePath, imageSaveParent[type]+'.'+fileType, "image/png", imageSaveParent[type] || "coachRegister", phone || 0)
              .then(async (uploadResult: any) => {
                if (uploadResult && uploadResult.code === 200) {
                  const { url, file_name } = uploadResult.data;
                  console.log(`上传 ${type} 成功: ${url}`);
                  // 根据类型更新对应的状态
                  switch (type) {
                    case 'coachLicense':
                      setCoachLicense({ url, file_name });
                      Taro.showToast({ title: '教练证上传成功', icon: 'success', duration: 1500 });
                      await recognizeCoachLicenseInfo(url);
                      setShowCoachingTypeField(true);
                      break;
                    case 'idCardFront':
                      setIdCardFront({ url, file_name });
                      Taro.showToast({ title: '身份证正面上传成功', icon: 'success', duration: 1500 });
                      await recognizeIdCardInfo(url);
                      break;
                    case 'idCardBack':
                      setIdCardBack({ url, file_name });
                      Taro.showToast({ title: '身份证国徽面上传成功', icon: 'success', duration: 1500 });
                      break;
                    case 'avatar':
                      setAvatar({ url, file_name });
                      Taro.showToast({ title: '头像上传成功', icon: 'success', duration: 1500 });
                      break;
                    case 'businessLicense':
                      setBusinessLicense({ url, file_name });
                      Taro.showToast({ title: '营业执照上传成功', icon: 'success', duration: 1500 });
                      break;
                  }
                } else {
                  Taro.showToast({ 
                    title: uploadResult.message || '图片上传失败，请重试', 
                    icon: 'none', 
                    duration: 2000 
                  });
                }
              })
          } catch (error) {
            Taro.showToast({ 
              title: error.message || '图片上传失败，请重试', 
              icon: 'none', 
              duration: 2000 
            });
          } finally {
            Taro.hideLoading();
          }
        }
      });
    } catch (error) {
      console.error('选择图片失败:', error);
      Taro.showToast({
        title: '选择图片失败',
        icon: 'none',
      });
    }
  };

  // 身份证信息识别函数
  const recognizeIdCardInfo = async (key: string) => {
    Taro.showLoading({ title: '识别信息中...' });
    try {
      await getIdCardOcrApi(key, 'FRONT', idUid).then((res) => {
        console.log(res.code, res.data?.success);
        if(res.code == 200 && res.data?.success) {
          const ocrResult = res.data;
          setIdCardFront(key);
          setIdUid(ocrResult.uid || "");
          // 显示姓名、性别和籍贯字段
          setShowNameField(true);
          setShowGenderField(true);
          setShowNativeField(true);
          if (ocrResult.name) setName(ocrResult.name);
          if (ocrResult.sex) setGender(ocrResult.sex);
          if (ocrResult.nation) setNative(ocrResult.nation);
          Taro.showToast({
            title: '身份证信息已自动填充',
            icon: 'success',
            duration: 2000,
          });
        }else{
          Taro.showToast({
            title: res.message + "  请重新上传！" || '身份证信息识别失败，请重新上传',
            icon: 'none',
          });
          setName("");
          setGender("");
          setNative("");
          setIdCardFront("");
          setShowNameField(false);
          setShowGenderField(false);
          setShowNativeField(false);
        }
      });
    } catch (error) {
      console.error('身份证信息识别失败:', error);
      Taro.showToast({
        title: '身份证信息识别失败，请重新上传',
        icon: 'none',
      });
    }
    finally {
      Taro.hideLoading();
    }
  };
  
  
  // 教练证信息识别函数
  const recognizeCoachLicenseInfo = async (key: string) => {
    try {
      Taro.showLoading({ title: '识别教练证信息中...' });
      
      // 调用教练证OCR API
      const response = await getCoachLicenseOcrApi(key);
      if (response.code === 200 && response.data && response.data.success) {
        const ocrResult = response.data;
        // 填充识别的执教类型
        if (ocrResult.license) {
          setCoachingType(ocrResult.license);
        }
        
        // 保存识别的教练姓名用于一致性验证
        if (ocrResult.name && name &&ocrResult.name !== name) {
          Taro.showToast({
            title: '身份证姓名与教练证姓名不一致，请核对',
            icon: 'none',
          });
        }

        Taro.showToast({
          title: '教练证信息已自动填充',
          icon: 'success',
          duration: 2000,
        });
      } else {
        throw new Error(response.data?.message || 'OCR识别失败');
      }
    } catch (error) {
      console.error('教练证信息识别失败:', error);
      Taro.showToast({
        title: '教练证信息识别失败，请手动填写执照类型',
        icon: 'none',
      });
    }
  };

  // 表单验证函数
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};
    
    if (!name.trim()) {
      errors.name = '请输入姓名';
    }
    if (!gender) {
      errors.gender = '请选择性别';
    }
    if (!city) {
      errors.city = '请选择城市';
    }
    if (!base_id) {
      errors.base = '请选择基地';
    }
    if (!drivingSchool.trim()) {
      errors.drivingSchool = '请输入驾校名称';
    }
    if (!coachingType) {
      errors.coachingType = '请选择执教类型';
    }
    if (coachingAge && (isNaN(Number(coachingAge)) || Number(coachingAge) < 1)) {
      errors.coachingAge = '教龄必须为大于0的数字';
    }
    if (!idCardFront) {
      errors.idCardFront = '请上传身份证正面照';
    }
    if (!idCardBack) {
      errors.idCardBack = '请上传身份证国徽面';
    }
    if (!coachLicense) {
      errors.coachLicense = '请上传教练证';
    }
    if (!avatar) {
      errors.avatar = '请上传头像';
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };
  
  // 表单提交函数
  const handleSubmit = async () => {
    // 表单验证
    if (!validateForm()) {
      Taro.showToast({ 
        title: "请填写完整信息", 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    setUploading(true);
    try {
      Taro.showLoading({ title: '提交中...' });
      await registerCoachUserApi({        
        phone,        
        username:name,        
        gender,        
        cityId:city,        
        baseId:base_id, 
        baseName:base_name,       
        school:drivingSchool,        
        licenses:coachingType,        
        idCardFront: idCardFront?.file_name || '',        
        idCardBack: idCardBack?.file_name || '',        
        certificate: coachLicense?.file_name || '',        
        avatar: avatar?.file_name || '',        
        schoolCertificate: businessLicense?.file_name || '',       
        sessionKey: sessionKeyDecoded || '',        
        native: native || '',        
        description: simulationFee || "",        
        englishTeaching: isEnglishTeaching,        
        experience_years: coachingAge || 0      
      }).then((res) => {
        if (res.code === 200) {
          Taro.showToast({
            title: '注册成功，请耐心等待管理员审核~',
            icon: 'success',
            duration: 2000,
          });
          setSubmitOver(true);
        } else {
          Taro.showToast({
            title: res.message || '注册失败',
            icon: 'none',
            duration: 2000,
          });
        }
      });
    } catch (error) {
      Taro.hideLoading();
      Taro.showToast({
        title: '网络错误，请检查网络连接',
        icon: 'none',
        duration: 2000,
      });
      console.error('提交注册信息失败:', error);
    } finally {
      // 无论成功失败，都要重置上传状态
      setUploading(false);
    }
  };

  return (
    <View className="coach-register-container" style={{backgroundImage: `url(${IMAGE_BASE_URL}/public/images/login-bg.png)`}}>
      <View className="coach-register-form">
        <View className="coach-register-header">
          <Text className="coach-register-title">教练注册</Text>
          <Text className="coach-register-subtitle">完善信息，成为认证教练</Text>
        </View>

        <View className="form-section">
          <View className="tip-card">
            <Text className="tip-title">📝 温馨提示</Text>
            <Text className="tip-content">
              请确保所有信息真实有效，上传的证件照片请保持清晰完整，以便快速通过审核。
            </Text>
          </View>
        </View>

        {/* 城市选择 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              城市 <Text className="required-mark">*</Text>
            </Text>
            <ProvinceCitySelector 
              level="region"
              chinaRegions={chinaCity}
              onSelect={handleRegionSelect}
              selectedRegionPath={selectedRegionPath}
            >
              <View className={`picker-field-wrapper ${formErrors.city ? 'error' : ''}`}>
                <Text>{city ? getCityName(city): '请选择城市'}</Text>
                <Text className="register-picker-arrow">▼</Text>
              </View>
            </ProvinceCitySelector>
            {formErrors.city && <Text className="error-message">{formErrors.city}</Text>}
          </View>
        </View>

        {/* 基地选择 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              基地 <Text className="required-mark">*</Text>
            </Text>
            <View>
              <Picker
                mode="selector"
                range={basesData.length > 0 ? basesData.map(base => `【${base.name}】 ${base.address}`) : ['当前城市暂无可用基地']}
                value={base_id && basesData.length > 0 ? basesData.findIndex(base => String(base.id) === String(base_id)) : 0}
                onChange={(e) => { 
                  if (basesData.length > 0) {
                    setBaseId(basesData[e.detail.value].id);
                  } else {
                    setBaseId('');
                  }
                }}
              >
                <View className={`picker-field ${formErrors.base ? 'error' : ''}`}>
                  {base_id ? 
                    `${basesData.find(base => String(base.id) === String(base_id))?.name || ''}` : 
                    (basesData.length > 0 ? '请选择基地' : '当前城市暂无可用基地')}
                  <Text className="register-picker-arrow">▼</Text>
                </View>
              </Picker>
            </View>
            {formErrors.base && <Text className="error-message">{formErrors.base}</Text>}
          </View>
        </View>

        {/* 驾校名称 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              驾校名称 <Text className="required-mark">*</Text>
            </Text>
            <Input
              className={`input-field ${formErrors.drivingSchool ? 'error' : ''}`}
              placeholder="请填写您所在职的驾校全称"
              value={drivingSchool}
              onInput={(e) => setDrivingSchool(e.detail.value)}
            />
            {formErrors.drivingSchool && <Text className="error-message">{formErrors.drivingSchool}</Text>}
          </View>
        </View>

        <View className="separator"></View>

        {/* 头像上传 */}
        <View className="form-section">
          <Text className="form-label">
            上传头像 <Text className="required-mark">*</Text>
          </Text>
          <View 
            className={`image-upload-container ${formErrors.avatar ? 'error' : ''}`}
            onClick={() => handleImageUpload('avatar')}
          >
            <View className="image-upload-placeholder">
              {avatar ? (
                <ImageLoader 
                  src={avatar.url} 
                  className="uploaded-image" 
                  mode="heightFix" 
                />
              ) : (
                <>
                  <Image 
                    mode="heightFix" 
                    src={`${IMAGE_BASE_URL}/public/images/avatar-upload.png`} 
                    className="register-camera-icon" 
                  />
                </>
              )}
            </View>
            <Text className="image-upload-text">
              {avatar ? '已上传头像' : '上传个人头像'}
            </Text>
          </View>
          {formErrors.avatar && <Text className="error-message">{formErrors.avatar}</Text>}
        </View>

        {/* 身份证上传 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              上传本人身份证明 <Text className="required-mark">*</Text>
            </Text>
            <View className="id-card-upload">
              {/* 身份证人像面 */}
              <View 
                className={`id-card-front image-upload-container ${formErrors.idCardFront ? 'error' : ''}`}
                onClick={() => handleImageUpload('idCardFront')}
              >
                <View className="image-upload-placeholder">
                  {idCardFront ? (
                    <ImageLoader 
                      src={idCardFront.url} 
                      className="uploaded-image id-card-image" 
                      mode="aspectFill" 
                    />
                  ) : (
                    <>
                      <Image 
                        mode="heightFix" 
                        src={`${IMAGE_BASE_URL}/public/images/idcard-front.png`} 
                        className="register-camera-icon" 
                      />
                    </>
                  )}
                </View>
                <Text className="image-upload-text">
                  {idCardFront ? '已上传' : '上传身份证正面照 (自动识别信息)'}
                </Text>
                {formErrors.idCardFront && <Text className="error-message">{formErrors.idCardFront}</Text>}
              </View>
              
              {/* 身份证国徽面 */}
              <View 
                className={`id-card-back image-upload-container ${formErrors.idCardBack ? 'error' : ''}`}
                onClick={() => handleImageUpload('idCardBack')}
              >
                <View className="image-upload-placeholder">
                  {idCardBack ? (
                    <ImageLoader 
                      src={idCardBack.url} 
                      className="uploaded-image id-card-image" 
                      mode="aspectFill" 
                    />
                  ) : (
                    <>
                      <Image 
                        mode="heightFix" 
                        src={`${IMAGE_BASE_URL}/public/images/idcard-back.png`} 
                        className="register-camera-icon" 
                      />
                    </>
                  )}
                </View>
                <Text className="image-upload-text">
                  {idCardBack ? '已上传' : '上传身份证国徽面'}
                </Text>
                {formErrors.idCardBack && <Text className="error-message">{formErrors.idCardBack}</Text>}
              </View>
            </View>
          </View>
        </View>

        
        {/* 姓名输入 - 移到身份证下方，初始隐藏 */}
        {showNameField && (
          <View className="form-section">
            <View className="form-field-container">
              <Text className="form-label">
                姓名 <Text className="required-mark">*</Text> <Text className="auto-fill-tip">(自动填充，需与教练证姓名一致)</Text>
              </Text>
              <Input
                className={`input-field ${formErrors.name ? 'error' : ''}`}
                placeholder="请输入您的真实姓名"
                value={name}
                onInput={(e) => setName(e.detail.value)}
              />
              {formErrors.name && <Text className="error-message">{formErrors.name}</Text>}
            </View>
          </View>
        )}

        {/* 性别选择 - 移到身份证下方，初始隐藏 */}
        {showGenderField && (
          <View className="form-section">
            <View className="form-field-container">
              <Text className="form-label">
                性别 <Text className="required-mark">*</Text> <Text className="auto-fill-tip">(自动填充)</Text>
              </Text>
              <View className={`radio-group ${formErrors.gender ? 'error' : ''}`}>
                <View 
                  className={`radio-item ${gender === '男' ? 'active' : ''}`}
                  onClick={() => setGender('男')}
                >
                  <View className={`radio-circle ${gender === '男' ? 'active' : ''}`}></View>
                  <Text>男</Text>
                </View>
                <View 
                  className={`radio-item ${gender === '女' ? 'active' : ''}`}
                  onClick={() => setGender('女')}
                >
                  <View className={`radio-circle ${gender === '女' ? 'active' : ''}`}></View>
                  <Text>女</Text>
                </View>
              </View>
              {formErrors.gender && <Text className="error-message">{formErrors.gender}</Text>}
            </View>
          </View>
        )}


        {/* 教练证上传 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              上传教练证 <Text className="required-mark">*</Text>
            </Text>
            <View 
              className={`image-upload-container ${formErrors.coachLicense ? 'error' : ''}`}
              onClick={() => handleImageUpload('coachLicense')}
            >
              <View className="image-upload-placeholder">
                {coachLicense ? (
                  <ImageLoader 
                    src={coachLicense.url} 
                    className="uploaded-image" 
                    mode="aspectFill" 
                  />
                ) : (
                  <>
                    <Image 
                      mode="heightFix" 
                      src={`${IMAGE_BASE_URL}/public/images/coach-license.png`} 
                      className="register-camera-icon" 
                    />
                  </>
                )}
              </View>
              <Text className="image-upload-text">
                {coachLicense ? '已上传教练证件' : '上传有效教练证件 (自动识别执照类型)'}
              </Text>
              {formErrors.coachLicense && <Text className="error-message">{formErrors.coachLicense}</Text>}
            </View>
          </View>
        </View>
        
        {/* 执教类型 - 移到教练证下方，初始隐藏 */}
        {showCoachingTypeField && (
          <View className="form-section">
            <View className="form-field-container">
              <Text className="form-label">
                执教类型 <Text className="required-mark">*</Text> <Text className="auto-fill-tip">(自动填充)</Text>
              </Text>
              <View>
                <Picker
                  mode="selector"
                  range={Object.keys(carLicenseList || [])}
                  onChange={(e) => setCoachingType(Object.keys(carLicenseList || [])[e.detail.value])}
                  value={carLicenseList && coachingType ? Math.max(0, Object.keys(carLicenseList).indexOf(coachingType)) : 0}
                >
                  <View className={`picker-field ${formErrors.coachingType ? 'error' : ''}`}>
                    <Text className={coachingType ? "picker-text" : "picker-placeholder"}>
                      {coachingType ? `${coachingType}[${carLicenseList?.[coachingType]?.name}]` : '请选择执教类型'}
                    </Text>
                  </View>
                </Picker>
              </View>
              {formErrors.coachingType && <Text className="error-message">{formErrors.coachingType}</Text>}
            </View>
          </View>
        )}

        {/* 营业执照上传（可选） */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              上传驾校营业执照（可选）
            </Text>
            <View 
              className="image-upload-container"
              onClick={() => handleImageUpload('businessLicense')}
            >
              <View className="image-upload-placeholder">
                {businessLicense ? (
                  <ImageLoader 
                    src={businessLicense.url} 
                    className="uploaded-image" 
                    mode="aspectFill" 
                  />
                ) : (
                  <>
                    <Image 
                      mode="heightFix" 
                      src={`${IMAGE_BASE_URL}/public/images/company-license.png`} 
                      className="register-camera-icon" 
                    />
                  </>
                )}
              </View>
              <Text className="image-upload-text">
                {businessLicense ? '已上传营业执照' : '上传驾校营业执照（可选）'}
              </Text>
            </View>
          </View>
        </View>
 
        {/* 籍贯输入 - 移到身份证下方，初始隐藏 */}
        {showNativeField && (
          <View className="form-section">
            <View className="form-field-container">
              <Text className="form-label">
                籍贯 <Text className="auto-fill-tip">(自动填充)</Text>
              </Text>
              <Input
                className={`input-field ${formErrors.native ? 'error' : ''}`}
                placeholder="请输入您的籍贯"
                value={native}
                onInput={(e) => setNative(e.detail.value)}
              />
              {formErrors.native && <Text className="error-message">{formErrors.native}</Text>}
            </View>
          </View>
        )}

        {/* 英语技能选择 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              是否英语教学
            </Text>
            <View className="radio-group">
              <View 
                className={`radio-item ${isEnglishTeaching === 1 ? 'active' : ''}`}
                onClick={() => setIsEnglishTeaching(1)}
              >
                <View className={`radio-circle ${isEnglishTeaching === 1 ? 'active' : ''}`}></View>
                <Text>是</Text>
              </View>
              <View 
                className={`radio-item ${isEnglishTeaching === 2 ? 'active' : ''}`}
                onClick={() => setIsEnglishTeaching(2)}
              >
                <View className={`radio-circle ${isEnglishTeaching === 2 ? 'active' : ''}`}></View>
                <Text>否</Text>
              </View>
            </View>
            {formErrors.isEnglishTeaching && <Text className="error-message">{formErrors.isEnglishTeaching}</Text>}
          </View>
        </View>

        {/* 教龄输入 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              教龄（可选）
            </Text>
            <View className="number-input-container">
              <Input
                className={`input-field number-input ${formErrors.coachingAge ? 'error' : ''}`}
                placeholder="请输入教龄（年）"
                value={coachingAge}
                onInput={(e) => setCoachingAge(e.detail.value)}
                type="number"
              />
            </View>
            {formErrors.coachingAge && <Text className="error-message">{formErrors.coachingAge}</Text>}
          </View>
        </View>

        {/* 模拟费用 */}
        <View className="form-section">
          <View className="form-field-container">
            <Text className="form-label">
              模拟费用（可选）
            </Text>
            <Input
              className="input-field"
              placeholder="如 科二150/一圈 科三600/畅模"
              value={simulationFee}
              onInput={(e) => setSimulationFee(e.detail.value)}
            />
          </View>
        </View>


        {/* 提交按钮 */}
        <Button 
          className={`register-submit-button ${uploading || submitOver ? 'register-submit-disabled' : ''}`}
          onClick={handleSubmit}
          loading={uploading}
          disabled={uploading || submitOver}
        >
          {uploading ? '提交中...' : '确认上传'}
        </Button>

        {/* 提示信息 */}
        <Text className="register-upload-tip">所有图片仅用于审核以及公安备案；平台确保您的信息安全</Text>
      </View>

    </View>
  );
};

export default CoachRegisterPage;
